clear
set more off

tempfile main bootsave 

insheet using encounters.csv, comma
rename year1 year
sort year month
save encounters, replace
clear

use covered_months_all
sort year month
merge 1:1 year month using encounters
drop _merge
* construct the dummies used in analysis
gen encounters=c
keep if year>=2006
gen trend=12*(year-2004)+month
gen counts=(encounters/(covered_lives/1000))
gen after2006=year>=2006
qui save `main' , replace 

postfile bskeep trend sse2 Fval using quadratic_spline_encounter_results_1, replace


forvalues b = 49/108 { 
	display `b'
	use `main', replace 
	gen z=trend-`b'
	gen post=trend>=`b'
	gen zpost1=post*z
	gen zpost2=zpost1*zpost1
	gen zpre1=(1-post)*z
	gen zpre2=zpre1*zpre1

	reg counts zpre1 zpre2 zpost1 zpost2
	local sse2=e(rss)
	test (zpre1=zpost1) (zpre2=zpost2)
	local Fval = r(F)
	post bskeep (`b') (`sse2') (`Fval')
}
postclose bskeep
clear
use quadratic_spline_encounter_results_1
sort trend
save, replace
list
clear

use `main', replace
sort trend
merge 1:1 trend using quadratic_spline_encounter_results_1
egen minsse2=min(sse2)
gen m2=minsse2==sse2
egen t2=max(m2*trend)

gen z=trend-t2
gen post=trend>=t2
gen zpost1=post*z
gen zpost2=zpost1*zpost1
gen zpre1=(1-post)*z
gen zpre2=zpre1*zpre1
reg counts zpre1 zpre2 zpost1 zpost2
test (zpre1=zpost1) (zpre2=zpost2)
predict countsp
drop z post zpost* zpre*

keep year month trend counts countsp sse2 t2 Fval
outsheet using quadratic_spline_encounter_results_1.csv, comma replace



